import { create } from 'zustand';
import { persist, createJSONStorage } from 'zustand/middleware';

export type ThemeMode = 'light' | 'dark';

interface ThemeState {
  mode: ThemeMode;
  toggleTheme: () => void;
  setTheme: (mode: ThemeMode) => void;
}

export const useThemeStore = create<ThemeState>()(
  persist(
    (set, get) => ({
      mode: 'dark', // 默认为深色主题
      toggleTheme: () => {
        const currentMode = get().mode;
        const newMode = currentMode === 'dark' ? 'light' : 'dark';
        set({ mode: newMode });
        // 更新DOM上的data-theme属性
        if (typeof document !== 'undefined') {
          document.documentElement.setAttribute('data-theme', newMode);
        }
      },
      setTheme: (mode: ThemeMode) => {
        set({ mode });
        // 更新DOM上的data-theme属性
        if (typeof document !== 'undefined') {
          document.documentElement.setAttribute('data-theme', mode);
        }
      },
    }),
    {
      name: 'theme-storage', // localStorage key
      storage: createJSONStorage(() => localStorage),
      // 避免在服务端渲染时访问localStorage
      skipHydration: typeof window === 'undefined',
      // 添加版本控制以避免缓存问题
      version: 1,
      migrate: (persistedState: any, version: number) => {
        // 如果版本是0或者没有版本，则执行迁移
        if (version === 0 || version === undefined) {
          // 返回默认状态，或者根据需要迁移旧状态
          return {
            mode: 'dark',
            ...persistedState,
          };
        }
        return persistedState;
      },
    }
  )
);